<template>
  <div>
    <el-tabs type="border-card">
      <el-tab-pane label="秒" v-if="shouldHide('second')">
        <CrontabSecond
          @update="updateCrontabValue"
          :check="checkNumber"
          :cron="state.crontabValueObj"
          ref="cronsecond"
        />
      </el-tab-pane>

      <el-tab-pane label="分钟" v-if="shouldHide('min')">
        <CrontabMin
          @update="updateCrontabValue"
          :check="checkNumber"
          :cron="state.crontabValueObj"
          ref="cronmin"
        />
      </el-tab-pane>

      <el-tab-pane label="小时" v-if="shouldHide('hour')">
        <CrontabHour
          @update="updateCrontabValue"
          :check="checkNumber"
          :cron="state.crontabValueObj"
          ref="cronhour"
        />
      </el-tab-pane>

      <el-tab-pane label="日" v-if="shouldHide('day')">
        <CrontabDay
          @update="updateCrontabValue"
          :check="checkNumber"
          :cron="state.crontabValueObj"
          ref="cronday"
        />
      </el-tab-pane>

      <el-tab-pane label="月" v-if="shouldHide('month')">
        <CrontabMonth
          @update="updateCrontabValue"
          :check="checkNumber"
          :cron="state.crontabValueObj"
          ref="cronmonth"
        />
      </el-tab-pane>

      <el-tab-pane label="周" v-if="shouldHide('week')">
        <CrontabWeek
          @update="updateCrontabValue"
          :check="checkNumber"
          :cron="state.crontabValueObj"
          ref="cronweek"
        />
      </el-tab-pane>

      <el-tab-pane label="年" v-if="shouldHide('year')">
        <CrontabYear
          @update="updateCrontabValue"
          :check="checkNumber"
          :cron="state.crontabValueObj"
          ref="cronyear"
        />
      </el-tab-pane>
    </el-tabs>

    <div class="popup-main">
      <div class="popup-result">
        <p class="title">时间表达式</p>
        <table>
          <thead>
            <th v-for="item of state.tabTitles" width="40" :key="item">
              {{ item }}
            </th>
            <th>Cron 表达式</th>
          </thead>
          <tbody>
            <td>
              <span>{{ state.crontabValueObj.second }}</span>
            </td>
            <td>
              <span>{{ state.crontabValueObj.min }}</span>
            </td>
            <td>
              <span>{{ state.crontabValueObj.hour }}</span>
            </td>
            <td>
              <span>{{ state.crontabValueObj.day }}</span>
            </td>
            <td>
              <span>{{ state.crontabValueObj.month }}</span>
            </td>
            <td>
              <span>{{ state.crontabValueObj.week }}</span>
            </td>
            <td>
              <span>{{ state.crontabValueObj.year }}</span>
            </td>
            <td>
              <span>{{ state.crontabValueString }}</span>
            </td>
          </tbody>
        </table>
      </div>
      <CrontabResult :ex="crontabValueString"></CrontabResult>

      <div class="pop_btn">
        <el-button size="small" type="primary" @click="submitFill"
          >确定</el-button
        >
        <el-button size="small" type="warning" @click="clearCron"
          >重置</el-button
        >
        <el-button size="small" @click="hidePopup">取消</el-button>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, defineEmits, onMounted, computed, watch } from "vue";
import CrontabSecond from "/@/components/Crontab/second.vue";
import CrontabMin from "/@/components/Crontab/min.vue";
import CrontabHour from "/@/components/Crontab/hour.vue";
import CrontabDay from "/@/components/Crontab/day.vue";
import CrontabMonth from "/@/components/Crontab/month.vue";
import CrontabWeek from "/@/components/Crontab/week.vue";
import CrontabYear from "/@/components/Crontab/year.vue";
import CrontabResult from "/@/components/Crontab/result.vue";

const emit = defineEmits(["hide", "fill"]);
const cronsecond = ref("");
const cronmin = ref("");
const cronhour = ref("");
const cronday = ref("");
const cronmonth = ref("");
const cronweek = ref("");
const cronyear = ref("");
const $refs = (refName: any) => {
  if (refName == "cronsecond") {
    return cronsecond.value;
  } else if (refName == "cronmin") {
    return cronmin.value;
  } else if (refName == "cronhour") {
    return cronhour.value;
  } else if (refName == "cronday") {
    return cronday.value;
  } else if (refName == "cronmonth") {
    return cronmonth.value;
  } else if (refName == "cronweek") {
    return cronweek.value;
  } else if (refName == "cronyear") {
    return cronyear.value;
  }
};
const state: any = reactive({
  tabTitles: ["秒", "分钟", "小时", "日", "月", "周", "年"],
  tabActive: 0,
  myindex: 0,
  crontabValueObj: {
    second: "*",
    min: "*",
    hour: "*",
    day: "*",
    month: "*",
    week: "?",
    year: "",
  },
});

let props: any = defineProps({
  expression: {
    type: String,
    required: true,
  },
  hideComponent: {
    type: String,
    required: true,
  },
});
const shouldHide = (key?: any) => {
  if (props.hideComponent && props.hideComponent.includes(key)) return false;
  return true;
};
const resolveExp = () => {
  // 反解析 表达式
  if (props.expression) {
    let arr = props.expression.split(" ");
    if (arr.length >= 6) {
      //6 位以上是合法表达式
      let obj: any = {
        second: arr[0],
        min: arr[1],
        hour: arr[2],
        day: arr[3],
        month: arr[4],
        week: arr[5],
        year: arr[6] ? arr[6] : "",
      };
      state.crontabValueObj = {
        ...obj,
      };
      for (let i in obj) {
        if (obj[i]) changeRadio(i, obj[i]);
      }
    }
  } else {
    // 没有传入的表达式 则还原
    clearCron();
  }
};
// tab切换值
const tabCheck = (index?: any) => {
  state.tabActive = index;
};
// 由子组件触发，更改表达式组成的字段值
const updateCrontabValue = (name?: any, value?: any, from?: any) => {
  state.crontabValueObj[name] = value;
  // debugger
  if (from && from !== name) {
    changeRadio(name, value);
  }
};
// 赋值到组件
const changeRadio = (name?: any, value?: any) => {
  let arr: any = ["second", "min", "hour", "month"],
    refName: any = "cron" + name,
    insValue: any;
  
  let refData: any = $refs(refName);
  if (!$refs(refName)) return;

  if (arr.includes(name)) {
    if (value === "*") {
      insValue = 1;
    } else if (value.indexOf("-") > -1) {
      let indexArr: any = value.split("-");
      isNaN(indexArr[0])
        ? (refData.cycle01 = 0)
        : (refData.cycle01 = indexArr[0]);
      refData.cycle02 = indexArr[1];
      insValue = 2;
    } else if (value.indexOf("/") > -1) {
      let indexArr = value.split("/");
      isNaN(indexArr[0])
        ? (refData.average01 = 0)
        : (refData.average01 = indexArr[0]);
      refData.average02 = indexArr[1];
      insValue = 3;
    } else {
      insValue = 4;
      refData.checkboxList = value.split(",");
    }
  } else if (name == "day") {
    if (value === "*") {
      insValue = 1;
    } else if (value == "?") {
      insValue = 2;
    } else if (value.indexOf("-") > -1) {
      let indexArr = value.split("-");
      isNaN(indexArr[0])
        ? (refData.cycle01 = 0)
        : (refData.cycle01 = indexArr[0]);
      refData.cycle02 = indexArr[1];
      insValue = 3;
    } else if (value.indexOf("/") > -1) {
      let indexArr = value.split("/");
      isNaN(indexArr[0])
        ? (refData.average01 = 0)
        : (refData.average01 = indexArr[0]);
      refData.average02 = indexArr[1];
      insValue = 4;
    } else if (value.indexOf("W") > -1) {
      let indexArr = value.split("W");
      isNaN(indexArr[0])
        ? (refData.workday = 0)
        : (refData.workday = indexArr[0]);
      insValue = 5;
    } else if (value === "L") {
      insValue = 6;
    } else {
      refData.checkboxList = value.split(",");
      insValue = 7;
    }
  } else if (name == "week") {
    if (value === "*") {
      insValue = 1;
    } else if (value == "?") {
      insValue = 2;
    } else if (value.indexOf("-") > -1) {
      let indexArr = value.split("-");
      isNaN(indexArr[0])
        ? (refData.cycle01 = 0)
        : (refData.cycle01 = indexArr[0]);
      refData.cycle02 = indexArr[1];
      insValue = 3;
    } else if (value.indexOf("#") > -1) {
      let indexArr = value.split("#");
      isNaN(indexArr[0])
        ? (refData.average01 = 1)
        : (refData.average01 = indexArr[0]);
      refData.average02 = indexArr[1];
      insValue = 4;
    } else if (value.indexOf("L") > -1) {
      let indexArr = value.split("L");
      isNaN(indexArr[0])
        ? (refData.weekday = 1)
        : (refData.weekday = indexArr[0]);
      insValue = 5;
    } else {
      refData.checkboxList = value.split(",");
      insValue = 6;
    }
  } else if (name == "year") {
    if (value == "") {
      insValue = 1;
    } else if (value == "*") {
      insValue = 2;
    } else if (value.indexOf("-") > -1) {
      insValue = 3;
    } else if (value.indexOf("/") > -1) {
      insValue = 4;
    } else {
      refData.checkboxList = value.split(",");
      insValue = 5;
    }
  }
  refData.radioValue = insValue;
};
// 表单选项的子组件校验数字格式（通过-props传递）
const checkNumber = (value?: any, minLimit?: any, maxLimit?: any) => {
  // 检查必须为整数
  value = Math.floor(value);
  if (value < minLimit) {
    value = minLimit;
  } else if (value > maxLimit) {
    value = maxLimit;
  }
  return value;
};
// 隐藏弹窗
const hidePopup = () => {
  emit("hide");
};
// 填充表达式
const submitFill = () => {
  emit("fill", crontabValueString.value);
  hidePopup();
};
const clearCron = () => {
  // 还原选择项
  state.crontabValueObj = {
    second: "*",
    min: "*",
    hour: "*",
    day: "*",
    month: "*",
    week: "?",
    year: "",
  };
  for (let j in state.crontabValueObj) {
    changeRadio(j, state.crontabValueObj[j]);
  }
};
const crontabValueString = computed(() => {
  let obj = state.crontabValueObj;
  let str =
    obj.second +
    " " +
    obj.min +
    " " +
    obj.hour +
    " " +
    obj.day +
    " " +
    obj.month +
    " " +
    obj.week +
    (obj.year == "" ? "" : " " + obj.year);
  return str;
});
watch(props.expression, () => {
  resolveExp();
});
onMounted(() => {
  resolveExp();
});
</script>

<style scoped>
.pop_btn {
  text-align: center;
  margin-top: 20px;
}
.popup-main {
  position: relative;
  margin: 10px auto;
  /* background: #fff; */
  border-radius: 5px;
  font-size: 12px;
  overflow: hidden;
}
.popup-title {
  overflow: hidden;
  line-height: 34px;
  padding-top: 6px;
  /* background: #f2f2f2; */
}
.popup-result {
  box-sizing: border-box;
  line-height: 24px;
  margin: 25px auto;
  padding: 15px 10px 10px;
  border: 1px solid var(--el-border-color);
  position: relative;
}
.popup-result .title {
  position: absolute;
  top: -28px;
  left: 50%;
  width: 140px;
  font-size: 14px;
  margin-left: -70px;
  text-align: center;
  line-height: 30px;
  /* background: #fff; */
}
.popup-result table {
  text-align: center;
  width: 100%;
  margin: 0 auto;
}
.popup-result table span {
  display: block;
  width: 100%;
  font-family: arial;
  line-height: 30px;
  height: 30px;
  white-space: nowrap;
  overflow: hidden;
  border: 1px solid #e8e8e8;
    border: 1px solid var(--el-border-color);
}
.popup-result-scroll {
  font-size: 12px;
  line-height: 24px;
  height: 10em;
  overflow-y: auto;
}
</style>
